//
//  提交申请修改.m
//  xinhua_sx
//
//  Created by love on 14-8-15.
//  Copyright (c) 2014年 dangyangyang. All rights reserved.
//

#import "提交申请修改.h"
#import "AFNetworking.h"
#import "MBProgressHUD.h"
@implementation UIScrollView (UITouchEvent)

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [[self nextResponder] touchesBegan:touches withEvent:event];
    [super touchesBegan:touches withEvent:event];
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    [[self nextResponder] touchesMoved:touches withEvent:event];
    [super touchesMoved:touches withEvent:event];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    [[self nextResponder] touchesEnded:touches withEvent:event];
    [super touchesEnded:touches withEvent:event];
}
@end

#define LISTNAM @[@"职业",@"工作单位",@"部门",@"职务",@"专业",@"性格",@"子女个数",@"毕业院校",@"地址",@"邮箱",@"电话"]
#define NAme @[@"Profession",@"workUnit",@"section",@"duty",@"career",@"nature",@"chileNumber",@"school",@"adress",@"email",@"phone"]
@interface shenqinxiugai ()
{
    MBProgressHUD* HUD;
}
@property (nonatomic, strong) NSMutableArray* array;

@end

@implementation shenqinxiugai
@synthesize array;
@synthesize scro;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
-(void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    array = [[NSMutableArray alloc] init];
    CGFloat aY = kIOS_VERSION<7.0?0:20;
    UIView* _navBar = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, self.view.frame.size.width, 44.0+aY)];
    _navBar.backgroundColor = [UIColor colorWithRed:2.0/255 green:102.0/255 blue:172.0/255 alpha:1.0];
    _navBar.userInteractionEnabled = YES;
    
    UILabel* _titleLable = [[UILabel alloc] initWithFrame:CGRectMake(0, aY, self.view.frame.size.width, 44)];
    _titleLable.backgroundColor = [UIColor clearColor];
    _titleLable.textColor = [UIColor whiteColor];
    _titleLable.font = [UIFont systemFontOfSize:20];
    _titleLable.textAlignment = NSTextAlignmentCenter;
    _titleLable.text = @"提交申请修改";
    [_navBar addSubview:_titleLable];
    [self.view addSubview:_navBar];
    UIButton* _leftButton = [[UIButton alloc] initWithFrame:CGRectMake(0, aY, 40,40.0)];
    [_leftButton setImage:[UIImage imageNamed:@"icon_back@2x.png"] forState:UIControlStateNormal];
    
    _leftButton.imageEdgeInsets = UIEdgeInsetsMake(10, 13, 5, 5);
    [_leftButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_leftButton];
    self.view.backgroundColor = [UIColor whiteColor];
    UIScrollView* sc = [[UIScrollView alloc] initWithFrame:CGRectMake(0, aY+50, 320, self.view.frame.size.height-80)];
    [self.view addSubview:sc];
    self.scro = sc;
    for (int i =0 ; i <11; i ++)
    {
        UILabel* l1 = [[UILabel alloc] initWithFrame:CGRectMake(0, 10+i*25, 80, 20)];
        l1.backgroundColor = [UIColor clearColor];
        l1.textColor = [UIColor blackColor];
        l1.text = LISTNAM[i];
        l1.textAlignment = NSTextAlignmentRight;
        [sc addSubview:l1];
        
        
    }
    sc.contentSize = CGSizeMake(320, 550);
    UIButton* button1 = [[UIButton alloc] initWithFrame:CGRectMake(10, 10+11*25+30, 145, 30)];
    [button1 addTarget:self action:@selector(xiugai1) forControlEvents:UIControlEventTouchUpInside];
    [button1 setTitle:@"保存" forState:UIControlStateNormal];
    [scro addSubview:button1];
    UIButton* button2 = [[UIButton alloc] initWithFrame:CGRectMake(165, 10+11*25+30, 145, 30)];
    [button2 addTarget:self action:@selector(xiugai2) forControlEvents:UIControlEventTouchUpInside];
    [button2 setTitle:@"取消" forState:UIControlStateNormal];
    [scro addSubview:button2];
    [button1 setBackgroundColor:[shenqinxiugai colorWithHexString:@"#A6C4E8"]];
    [button2 setBackgroundColor:[shenqinxiugai colorWithHexString:@"#A6C4E8"]];
    [button1 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [button2 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self loadi];

    
    // Do any additional setup after loading the view.
}
-(void)xiugai1
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
    int count = 8;
    for (int i = 0; i < count; i ++)
    {
        UITextField* te = array[i];
        [te resignFirstResponder];
        if ([te.text length] == 0 )
        {
            [te becomeFirstResponder];
            UIAlertView* view = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请填写正确信息" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [view show];
            return;
            
        }
        if (i == 0 && [te.text intValue] < 0)
        {
            [te becomeFirstResponder];
            UIAlertView* view = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请填写正确年龄" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [view show];
            return;
        }
        
    }
    UITextField* t1 = [array objectAtIndex:1];
    UITextField* t2 = [array objectAtIndex:2];
    UITextField* t0 = array[0];
    UITextField* t3 = array[3];
    UITextField* t4 = array[4];
    UITextField* t5 = array[5];
    UITextField* t6 = array[6];
    UITextField* t7 = array[7];
    UITextField* t8 = array[8];
    UITextField* t9 = array[9];
    UITextField* t10 = array[10];
    if ([t10.text length] !=11)
    {
        [t4 becomeFirstResponder];
        UIAlertView* view = [[UIAlertView alloc] initWithTitle:@"提示" message:@"手机号码格式不对" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [view show];
        return;
    }
    if (![self validateEmail:t9.text])
    {
        [t5 becomeFirstResponder];
        UIAlertView* view = [[UIAlertView alloc] initWithTitle:@"提示" message:@"邮箱地址格式不对" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [view show];
        return;
    }
    
    NSString* uid = [[NSUserDefaults standardUserDefaults] objectForKey:@"UID"];
    if (!uid)
    {
        return;
    }
    
    // NSLog(@"dishi  =%@",_dizhistring);
    //NSDictionary* dic = @{@"code":@"149725", @"name":t0.text, @"password":t1.text, @"nickname":t3.text, @"phone":t4.text,@"email":t5.text,@"userRegIP":@"192.168.1.11",@"longitude":@"1",@"latitude":@"1"};
    NSString* st = [NSString stringWithFormat:@"http://183.203.18.45:7001/xinhua/m/modifyUserApply.html"];
    NSLog(@"st = %@",st);
    [HUD hide:YES];
    HUD = [[MBProgressHUD alloc] initWithView:self.view];
    HUD.labelText = @"正在保存";
    HUD.dimBackground = YES;
    [self.view addSubview:HUD];
    [HUD show:YES];
    //?%@=%@&%@=%@&%@=%@&%@=%@&%@=%@&%@=%@&%@=%@&%@=%@&marriage=否&frontUserId=%@",NAme[0],t0.text,NAme[1],t1.text,NAme[2],t2.text,NAme[3],t3.text,NAme[4],t4.text,NAme[5],t5.text,NAme[6],t6.text,NAme[7],t7.text,uid
    NSString*sff = COUTURYCODE;
    NSDictionary* dic = @{NAme[0]:t0.text,NAme[1]:t1.text,NAme[2]:t2.text,NAme[3]:t3.text,NAme[4]:t4.text,NAme[5]:t5.text,NAme[6]:t6.text,NAme[7]:t7.text,NAme[8]:t8.text ,NAme[9]:t9.text ,NAme[10]:t10.text ,@"frontUserId":uid,@"officeNumber":@"一级部门",@"family":@"family",@"lifeArae":@"寿阳",@"code":sff,@"title":@"公务员"};
    NSLog(@"dic = %@",dic);
    st = [st stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [manager POST:st parameters:dic success:^(AFHTTPRequestOperation*operation, id responseObject) {
        id jsonObject = [NSJSONSerialization JSONObjectWithData:operation.responseData
                                                        options:NSJSONReadingAllowFragments
                                                          error:nil];
        NSLog(@"json = %@",jsonObject);
        [HUD hide:YES];
        NSString* string = [NSString stringWithFormat:@"%@",jsonObject[@"result"]];
        if ([string isEqualToString:@"success"])
        {
            UIAlertView* v1 = [[UIAlertView alloc] initWithTitle:@"提示" message:jsonObject[@"message"] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
            v1.tag = 100086;
            [v1 show];
            // NSUserDefaults* de = [NSUserDefaults standardUserDefaults];
            // [de removeObjectForKey:@"UID"];
            // [de synchronize];
            
            NSLog(@"1222");
            //  [[NSNotificationCenter defaultCenter] postNotificationName:@"Logout1" object:nil];
            NSLog(@"2233");
        }
        else
        {
            UIAlertView* v1 = [[UIAlertView alloc] initWithTitle:@"提示" message:jsonObject[@"message"] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
            
            [v1 show];
        }
        //self.usreL.text = [jsonObject objectForKey:@"name"];
        //self.nameL.text = [jsonObject objectForKey:@"nickName"];
        //[self.ve setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://183.203.18.45:7001%@",jsonObject[@"qRcodePath"]]] placeholderImage:[UIImage imageNamed:@"base_detail_default_pic.png"]];
    } failure:^(AFHTTPRequestOperation *operation, NSError*error) {
        [HUD hide:YES];
        UIAlertView* v1 = [[UIAlertView alloc] initWithTitle:@"提示" message:@"保存失败!" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [v1 show];
        NSLog(@"error = %@",error);
    }];

}
- (BOOL) validateEmail: (NSString *) candidate {
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:candidate];
}
-(void)xiugai2
{
    [self back];
}
-(void)loadi
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
    NSString* uid = [[NSUserDefaults standardUserDefaults] objectForKey:@"UID"];
    
    NSString* sting = [NSString stringWithFormat:@"http://183.203.18.45:7001/xinhua/m/userShow.html"];

    [manager POST:sting parameters:[NSDictionary dictionaryWithObjectsAndKeys:uid,@"frontUserId", nil] success:^(AFHTTPRequestOperation*operation, id responseObject) {
        id jsonObject = [NSJSONSerialization JSONObjectWithData:operation.responseData
                                                        options:NSJSONReadingAllowFragments
                                                          error:nil];
        NSLog(@"json = %@",jsonObject);
        for (int i =0 ; i < 11; i ++)
        {
            
            UITextField* text = [[UITextField alloc] initWithFrame:CGRectMake(90, 10+i*25, 170, 20)];
            text.borderStyle = UITextBorderStyleRoundedRect;
            text.font = [UIFont systemFontOfSize:12];
            NSString* st = [NAme objectAtIndex:i];
            NSLog(@"st = %@",st);
            
            text.text = [NSString stringWithFormat:@"%@",[jsonObject objectForKey:st]];
            if ([text.text isEqualToString:@" "])
            {
                text.text = @"";
            }
            if (i == 6 && [text.text isEqualToString:@"-1"])
            {
                text.text = @"";
                text.keyboardType = UIKeyboardTypeNumberPad;
            }
            if (i ==10)
            {
                  text.keyboardType = UIKeyboardTypeNumberPad;
            }
            if ([text.text isEqualToString:@"(null)"])
            {
                 text.text = @"";
            }
            NSLog(@"text = %@",text.text);
            [self.scro addSubview:text];
            [array addObject:text];
            
        }

    } failure:^(AFHTTPRequestOperation *operation, NSError*error) {
        NSLog(@"error = %@",error);
    }];
    

}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    for (id item in array)
    {
        [item resignFirstResponder];
    }
}
+ (UIColor *) colorWithHexString: (NSString *)color
{
    NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    // String should be 6 or 8 characters
    if ([cString length] < 6) {
        return [UIColor clearColor];
    }
    
    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"])
        cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"])
        cString = [cString substringFromIndex:1];
    if ([cString length] != 6)
        return [UIColor clearColor];
    
    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    
    //r
    NSString *rString = [cString substringWithRange:range];
    
    //g
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    
    //b
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
